package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.client.article.IArticleClient;
import com.heima.client.user.IUserClient;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.pojos.ApCommentNew;
import com.heima.comment.service.BaiduScanService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.comment.dtos.CommentDto;
import com.heima.model.common.comment.dtos.CommentLikeDto;
import com.heima.model.common.comment.dtos.CommentSaveDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.article.ApArticleConfig;
import com.heima.model.common.pojos.user.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 杨尚杰
 * @data 2024/8/1 21:33
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private BaiduScanService baiduScanService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IUserClient userClient;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 保存评论
     *
     * @param commentSaveDto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto commentSaveDto) {
        //1.参数校验
        if(commentSaveDto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        //1.1判断是否可以评论
        ApArticleConfig articleConfig = articleClient.getArticleConfig(commentSaveDto.getArticleId());
        if (articleConfig.getIsComment().equals(false)){
            throw new CustomException(AppHttpCodeEnum.COMMENTS_ARE_NOT_ALLOWED);
        }
        //2.判断是否登录
        Integer userId = ApThreadLocalUtil.get();
        if(userId == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.评论内容不能超过140字
        if(commentSaveDto.getContent().length() > 140){
            throw new CustomException(AppHttpCodeEnum.TOO_MANY_WORDS);
        }
        //4.文本垃圾检测
        Integer scanText = baiduScanService.scanText(commentSaveDto.getContent());
        //审核结果类型，可取值1、2、3、4，分别代表1：合规，2：不合规，3：疑似，4：审核失败
        if(scanText != 1){
            throw new CustomException(AppHttpCodeEnum.VIOLATING_TEXT);
        }
        //5.根据作者保存
        ApUser user = userClient.getUser(userId);
        if(user == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        ApComment apComment = new ApComment();
        BeanUtils.copyProperties(commentSaveDto,apComment);
        apComment.setAuthorId(userId);
        apComment.setEntryId(commentSaveDto.getArticleId());
        apComment.setImage(user.getImage());
        apComment.setReply(0);
        apComment.setType((short)0);
        apComment.setFlag((short)0);
        apComment.setAuthorName(user.getName());
        apComment.setLikes(0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());


        //通过MongoDB保存
        mongoTemplate.save(apComment);

        int comment = 1;
        // 发送消息到kafka,将评论数量同步到ap_article
        Map<String,Object> map = new HashMap<>();
        map.put("articleId",commentSaveDto.getArticleId());
        map.put("comment",comment);
        kafkaTemplate.send("article_comment", JSON.toJSONString(map));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查询评论列表
     *
     * @param commentDto
     * @return
     */
    @Override
    public ResponseResult loadComment(CommentDto commentDto) {
        //1.参数校验
        if(commentDto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        //2.展示文章评论的列表,按时间倒叙排列
        Query query = Query.query(Criteria.where("entryId").is(commentDto.getArticleId())
                .and("createdTime").lt(commentDto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime")).limit(10);
        List<ApComment> comments = mongoTemplate.find(query, ApComment.class);
        //3.判断是否登录
        Integer userId = ApThreadLocalUtil.get();
        if(userId == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //4.获取所有评论的id
        List<String> commentIDs = comments.stream().map(apComment ->
                apComment.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId")
                .in(commentIDs).and("authorId").is(userId));
        //5.查询有点赞的
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);
        if(apCommentLikes == null){
            return ResponseResult.okResult(comments);
        }
        //6.返回给前端有点赞的列表
        List<ApCommentNew> apCommentNewList = new ArrayList<>();
        comments.forEach(apComment -> {
            ApCommentNew apCommentNew = new ApCommentNew();
            BeanUtils.copyProperties(apComment,apCommentNew);
            for (ApCommentLike apCommentLike : apCommentLikes) {
                if(apComment.getId().equals(apCommentLike.getCommentId())){
                    apCommentNew.setOperation(0);
                    break;
                }
            }
            apCommentNewList.add(apCommentNew);
        });
        return ResponseResult.okResult(apCommentNewList);

    }

    /*
     * 点赞
     *
     * @param commentLikeDto
     * @return
     */
    @Override
    public ResponseResult likeComment(CommentLikeDto commentLikeDto) {
        //1.参数校验
        if(commentLikeDto == null)
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        //2.判断是否登录
        Integer userId = ApThreadLocalUtil.get();
        if(userId == null){
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.获取所有评论的点赞数
        ApComment comments = mongoTemplate.findOne(Query.query(Criteria.where("id")
                .is(commentLikeDto.getCommentId())), ApComment.class);
        // 根据点赞操作增加或减少点赞数
        if(comments != null && commentLikeDto.getOperation() == 0){
            comments.setLikes(comments.getLikes() + 1);
            // 保存评论点赞数的更新
            mongoTemplate.save(comments);
            //将点赞信息同步到 ap_comment_like表中
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(userId);
            apCommentLike.setCommentId(commentLikeDto.getCommentId());
            mongoTemplate.save(apCommentLike);
        }else {
            //取消点赞
            Integer likes = comments.getLikes();
            if(likes -1 < 0){
                comments.setLikes(0);
            }else {
                comments.setLikes(comments.getLikes() -1);
            }
            // 保存评论点赞数的更新
            mongoTemplate.save(comments);
            //将点赞信息同步到 ap_comment_like表中
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(userId);
            apCommentLike.setCommentId(commentLikeDto.getCommentId());
            mongoTemplate.save(apCommentLike);
        }
        return ResponseResult.okResult(comments);
    }


}

